package cn.net.Thread;
/*
  优化方案；synchronized () { }加同步锁
 */
public class SoleTicketsV1 {
    public static void main(String[] args) {
        //
        TicketThread1_1 t1 = new TicketThread1_1();
        TicketThread1_1 t2 = new TicketThread1_1();
        TicketThread1_1 t3 = new TicketThread1_1();
        TicketThread1_1 t4 = new TicketThread1_1();

        //6.以多线程的方式启动
        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}
class TicketThread1_1 extends Thread{
//1.声明静态变量并赋值；静态资源属于类资源,被全局所有对象共享,只有一份
    static  int tickets =100;//四个线程共卖一百张
    //2.把业务写在重写run()里
    @Override
    public void run() {
        synchronized (TicketThread1_1.class) { //修改同步代码块的锁对象为成员变量o,注意,"唯一"很重要
            //3.业务需要while循环
            while (true) {
                if(tickets>0) {
                    //4.程序休眠10秒并检验安全隐患
                    try {
                        Thread.sleep(10);//try/catch
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //5.循环内直接调用getName()获取线程名和票号
                    System.out.println(getName() + "=" + tickets--);
                }
                //6.需循环的结束条件和中止条件
                if(tickets<=0) break;
            }
        }
    }
}